package com.xiaochong.tir.apiservice.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.apiservice.component.hbase.CurrencyInfoHbaseComponent;
import com.xiaochong.tir.apiservice.config.hbase.HbaseConnectionFactory;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.apiservice.service.CurrencyDiagnosisService;
import com.xiaochong.tir.apiservice.service.CurrencyGlobalInfoHbaseService;
import com.xiaochong.tir.apiservice.service.CurrencyInfoHbaseService;
import com.xiaochong.tir.apiservice.service.CurrencyInfoService;
import com.xiaochong.tir.apiservice.util.HttpUtils;
import com.xiaochong.tir.common.data.Bo.CurrencyGainPriceRedisBo;
import com.xiaochong.tir.common.data.hbasepo.*;
import com.xiaochong.tir.common.data.po.CurrencyGlobalInfoHbase;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.po.CurrencyInfoHbase;
import com.xiaochong.tir.common.data.vo.CmcGobalDataVo;
import com.xiaochong.tir.common.data.vo.CmcTickerDataVo;
import com.xiaochong.tir.common.exception.ErrorDataException;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseTablePutExcetion;
import com.xiaochong.tir.common.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by wujiaxing on 2018/4/24.
 */
@Component
public class CoinMarketCapDataComponent {


    @Value("${coinmarketcap.url.api.global}")
    private String globalUrl;

    @Value("${coinmarketcap.url.api.ticker}")
    private String tickerUrl;

    @Value("${coinmarketcap.url.api.currencies}")
    private String currenciesUrl;

    @Value("${google.trends.url}")
    private String googleTrendsUrl;

    @Autowired
    private HbaseConnectionFactory hbaseConnectionFactory;

    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;

    @Autowired
    private CurrencyInfoService currencyInfoService;

    @Autowired
    private CurrencyInfoHbaseService currencyInfoHbaseService;

    @Autowired
    private CurrencyGlobalInfoHbaseService currencyGlobalInfoHbaseService;


    @Autowired
    private CurrencyInfoHbaseComponent currencyInfoHbaseComponent;

    @Autowired
    private CurrencyDiagnosisService currencyDiagnosisService;

    @Autowired
    private RedisCacheComponent redisCacheComponent;

    @Autowired
    private RedisServer redisServer;


    /**
     * 获取cmc网站所有货币市值
     *
     * @param convert
     * @return
     * @throws IOException
     */
    public List<CmcCurrencyInfo> ticker(String convert) throws IOException {
        int i = 1;
        JSONObject jsonObject = new JSONObject();
        while (true) {
            String url = tickerUrl + "?";
            if (StringUtils.isNotBlank(convert)) {
                url = url + "convert=" + convert;
            }
            url = url + "&limit=" + 100;
            url = url + "&start=" + i;
            i += 100;
            String post = HttpUtils.get(url);
            if (StringUtils.isNotBlank(post)) {
                JSONObject resultJson = JSON.parseObject(post);
                JSONObject dataObject = resultJson.getJSONObject("data");
                if (CollectionUtil.isBlank(dataObject)) {
                    post = HttpUtils.get(url);
                    resultJson = JSON.parseObject(post);
                    dataObject = resultJson.getJSONObject("data");
                    if (CollectionUtil.isBlank(dataObject)) {
                        break;
                    }
                }
                jsonObject.putAll(dataObject);
            } else {
                break;
            }
        }
        if (jsonObject.size() == 0) {
            return null;
        }
        //System.out.println(jsonObject.toJSONString());
        LogTrace.info(LogTraceKeysUtils.COIN_MARKET_CAP_API_SCHEDULED_TITLE, LogTraceKeysUtils.DATA, "ticker调取cmc接口按成");
        return this.insertCurrencyInfo(jsonObject);
    }

    /**
     * 获取cmc全球数据
     *
     * @param convert
     * @return
     * @throws IOException
     */
    public CmcCurrencyGlobalInfo global(String convert) throws IOException {
        String url = globalUrl + "?";
        if (StringUtils.isNotBlank(convert)) {
            url = url + "convert=" + convert;
        }
        String post = HttpUtils.get(url);
        JSONObject jsonObject = JSONObject.parseObject(post);
        if (jsonObject.size() == 0) {
            return null;
        }
        return this.insertCurrencyGlobalInfo(jsonObject);
    }

    /**
     * 货币历史记录（开，收 盘价  最高最低价，交易量，市值）
     * @return
     */
    public boolean confirmTodayCurrencies() {
        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_NAME
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_FAMILY
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_QUALIFIER
                    , DateUtils.getCurrentDateString());
            JSONObject jsonObject;
            if (StringUtils.isBlank(data)) {
                return false;
            } else {
                jsonObject = JSON.parseObject(data);
                if (jsonObject == null || jsonObject.size() == 0) {
                    return false;
                }
                return true;
            }
        } catch (HbaseConnectionExcetion | IOException
                | HbaseGetTableExcetion | HbaseCloseExcetion e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 爬取cmc货币历史数据
     *
     * @return
     */
    public Map<String, List<CurrencyHistorical>> currencies() {
        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_NAME
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_FAMILY
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_QUALIFIER
                    , DateUtils.getNextDayDateYMD(-1));
            JSONObject jsonObject;
            if (StringUtils.isNotBlank(data)) {
                jsonObject = JSON.parseObject(data);
            } else {
                jsonObject = new JSONObject();
            }
            Date now = new Date();
            List<CurrencyInfo> currencyInfos = redisCacheComponent.getCurrencyList();
            Map<String, List<CurrencyHistorical>> map = new HashMap<>();
            if (currencyInfos != null && currencyInfos.size() > 0) {
                for (CurrencyInfo info : currencyInfos) {
                    try {
                        Map<String, List<DailyComprehensiveAnalysisInfo>> todayDailyCurrencyInfor
                                = this.getDailyCurrencyInfor(info.getCmcId() + "@" + DateUtils.getCurrentDateString());
                        Map<String, List<DailyComprehensiveAnalysisInfo>> yesterdayDailyCurrencyInfor
                                = this.getDailyCurrencyInfor(info.getCmcId() + "@" + DateUtils.getNextDayDateYMD(-1));

                        JSONArray jsonArray = jsonObject.getJSONArray(info.getCmcId());
                        List<CurrencyHistorical> yesterdayHistoricals;
                        List<CurrencyHistorical> historicals = new ArrayList<>();
                        if (jsonArray == null) {
                            yesterdayHistoricals = new ArrayList<>();
                        } else {
                            yesterdayHistoricals = jsonArray.toJavaList(CurrencyHistorical.class);
                        }
                        int size;
                        if (yesterdayHistoricals.size() < 30) {
                            size = yesterdayHistoricals.size();
                        } else {
                            size = 30;
                        }
                        for (int i = 0; i < size; i++) {
                            historicals.add(yesterdayHistoricals.get(i));
                        }
                        String key = "8";
                        CurrencyHistorical historical = new CurrencyHistorical();
                        historical.setId(info.getCmcId());
                        historical.setDate(now);
                        historical.setCreateTime(now);


                        if (CollectionUtil.isNotBlank(yesterdayDailyCurrencyInfor)) {
                            List<DailyComprehensiveAnalysisInfo> yestardayDailyInfors = yesterdayDailyCurrencyInfor.get(key);
                            if (CollectionUtils.isEmpty(yestardayDailyInfors)
                                    //|| MathUtils.isNotNumeric(yestardayDailyInfors.get(0).getPriceUsd())
                                    || MathUtils.isNotNumeric(yestardayDailyInfors.get(0).getPriceCny())) {
                                LogTrace.error(LogTraceKeysUtils.CURRENCIES, new ErrorDataException("获取前一日货币历史数据失败！"));
                            } else {
                                historical.setOpeningPriceCny(new BigDecimal(yestardayDailyInfors.get(0).getPriceCny()));
                            }

                        } else {
                            LogTrace.error(LogTraceKeysUtils.CURRENCIES, new ErrorDataException("获取前一日货币历史数据失败！"));
                        }


                        if (todayDailyCurrencyInfor == null) {
                            throw new ErrorDataException("获取当日货币历史数据失败null");
                            //LogTrace.info("定时任务", "获取当日货币历史数据失败！" + JSON.toJSONString(yesterdayDailyCurrencyInfor));
                        } else {
                            List<DailyComprehensiveAnalysisInfo> todayDailyInfors = todayDailyCurrencyInfor.get(key);
                            if (CollectionUtils.isEmpty(todayDailyInfors)
                                    //|| MathUtils.isNotNumeric(todayDailyInfors.get(0).getPriceUsd())
                                    || MathUtils.isNotNumeric(todayDailyInfors.get(0).getPriceCny())) {
                                //LogTrace.info("定时任务", "获取当日货币历史数据失败！" + JSON.toJSONString(todayDailyInfors));
                                if (LocalDateTime.now().getHour() >= 8) {
                                    throw new ErrorDataException("获取当日货币历史数据失败 " + key);
                                }
                            } else {
                                //historical.setClosingPriceUsd(new BigDecimal(todayDailyInfors.get(0).getPriceUsd()));
                                historical.setClosingPriceCny(new BigDecimal(todayDailyInfors.get(0).getPriceCny()));
                            }
                            if (MathUtils.isNumeric(todayDailyInfors.get(0).getMarketCapCny())) {
                                historical.setMarketValue(new BigDecimal(todayDailyInfors.get(0).getMarketCapCny()));
                            }

                            if (MathUtils.isNumeric(todayDailyInfors.get(0).getVolume24hCny())) {
                                historical.setTradingVolume(new BigDecimal(todayDailyInfors.get(0).getVolume24hCny()));
                            }
                        }

                        String coin_height_price_cny = redisServer.get(RedisKeysUtils.COIN_HEIGHT_PRICE_CNY + info.getCmcId());
                        redisServer.remove(RedisKeysUtils.COIN_HEIGHT_PRICE_CNY + info.getCmcId());
                        if (MathUtils.isNumeric(coin_height_price_cny)) {
                            historical.setHighestPriceCny(new BigDecimal(coin_height_price_cny));
                        }


                        String coin_low_price_cny = redisServer.get(RedisKeysUtils.COIN_LOW_PRICE_CNY + info.getCmcId());
                        redisServer.remove(RedisKeysUtils.COIN_LOW_PRICE_CNY + info.getCmcId());
                        if (MathUtils.isNumeric(coin_low_price_cny)) {
                            historical.setLowestPriceCny(new BigDecimal(coin_low_price_cny));
                        }

                        if (LocalDateTime.now().getHour() >= 8 && historical.getClosingPriceCny() != null) {
                            historicals.add(0, historical);
                        }
                        map.put(info.getCmcId(), historicals);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogTrace.error(e.getMessage(), e);
                    }

                }
            }
            if (map.size() == 0) {
                throw new ErrorDataException("获取货币历史数据失败！");

            }
            currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_NAME
                    , DateUtils.getCurrentDateString()
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_FAMILY
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_QUALIFIER
                    , JSON.toJSONString(map));
            return map;
        } catch (ErrorDataException | HbaseConnectionExcetion | IOException
                | HbaseGetTableExcetion | HbaseCloseExcetion e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 爬取cmc货币历史数据
     */
    public List<CurrencyHistorical> currenciesCurrency(String coinId, Date now) throws IOException {
        String url = currenciesUrl.replaceAll("\\{coinId\\}", coinId);
        String post = HttpUtils.get(url);
        String[] lines = post.split("\\n");
        int headLine = 0;
        for (int i = 0; i < lines.length; i++) {
            if ("<th class=\"text-left\">日期</th>".equals(lines[i])) {
                headLine = i;
                break;
            }
        }
        BigDecimal exchangeRate = new BigDecimal(6.3564);
        List<CurrencyHistorical> currencyHistoricals = new ArrayList<>();
        for (int i = headLine; i < lines.length; i++) {
            if ("<tr class=\"text-right\">".equals(lines[i])) {
                CurrencyHistorical historical = new CurrencyHistorical();
                historical.setId(coinId);
                historical.setCreateTime(now);
                if (StringUtils.isNotBlank(lines[i + 1])) {
                    String[] split1 = lines[i + 1].split("<td class=\"text-left\">");
                    if (split1.length > 1) {
                        String dateString = split1[1].split("</td>")[0];
                        historical.setDateString(dateString);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
                        Date parse = null;
                        try {
                            parse = dateFormat.parse(dateString);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        historical.setDate(parse);
                    }
                }
                if (StringUtils.isNotBlank(lines[i + 2])) {
                    String[] split = lines[i + 2].split("\"");
                    if (split.length > 1) {
                        String openingPriceUsdString = split[1];
                        if (MathUtils.isNumeric(openingPriceUsdString)) {

                            historical.setOpeningPriceCny(new BigDecimal(openingPriceUsdString).multiply(exchangeRate));//TODO
                        }
                    }
                }
                if (StringUtils.isNotBlank(lines[i + 3])) {
                    String[] split = lines[i + 3].split("\"");
                    if (split.length > 1) {
                        String highestPriceUsdString = split[1];
                        if (MathUtils.isNumeric(highestPriceUsdString)) {
                            BigDecimal bigDecimal = new BigDecimal(highestPriceUsdString);
                            historical.setHighestPriceCny(bigDecimal.multiply(exchangeRate));//TODO
                        }

                    }
                }
                if (StringUtils.isNotBlank(lines[i + 4])) {
                    String[] split = lines[i + 4].split("\"");
                    if (split.length > 1) {
                        String lowestPriceUsdString = split[1];
                        if (MathUtils.isNumeric(lowestPriceUsdString)) {
                            BigDecimal bigDecimal = new BigDecimal(lowestPriceUsdString);
                            historical.setLowestPriceCny(bigDecimal.multiply(exchangeRate));//TODO
                        }

                    }
                }
                if (StringUtils.isNotBlank(lines[i + 5])) {
                    String[] split = lines[i + 5].split("\"");
                    if (split.length > 1) {
                        String closingPriceUsdString = split[1];
                        if (MathUtils.isNumeric(closingPriceUsdString)) {
                            BigDecimal bigDecimal = new BigDecimal(closingPriceUsdString);
                            historical.setClosingPriceCny(bigDecimal.multiply(exchangeRate));//TODO
                        }

                    }
                }
                if (StringUtils.isNotBlank(lines[i + 6])) {
                    String[] split = lines[i + 6].split("\"");
                    if (split.length > 1) {
                        String tradingVolumeString = split[1];
                        if (MathUtils.isNumeric(tradingVolumeString)) {
                            BigDecimal bigDecimal = new BigDecimal(tradingVolumeString);
                            historical.setTradingVolume(bigDecimal);
                        }
                    }
                }
                if (StringUtils.isNotBlank(lines[i + 7])) {
                    String[] split = lines[i + 7].split("\"");
                    if (split.length > 1) {
                        String marketValueString = split[1];

                        if (MathUtils.isNumeric(marketValueString)) {
                            BigDecimal bigDecimal = new BigDecimal(marketValueString);
                            historical.setMarketValue(bigDecimal);
                        }
                    }
                }

                currencyHistoricals.add(historical);
            }
        }

        return currencyHistoricals;
    }


    public List<CmcCurrencyInfo> insertCurrencyInfo(JSONObject dataObject) {
        if (CollectionUtil.isBlank(dataObject)) {
            return null;
        }
        List<CmcCurrencyInfo> cmcCurrencyInfos = new ArrayList<>();
        try {
            Connection connection = hbaseConnectionFactory.getConnection();
            Table table = hbaseConnectionFactory.getTable(connection, HbaseTableUtils.CURRENCY_INFO_TABLE_NAME);
            List<Put> putList = new ArrayList<>();
            Date now = new Date();
            String nowString = DateUtils.dateFormatString(now, DateUtils.format_ymdhm);
            List<CurrencyInfoHbase> currencyInfoHbases = new ArrayList<>();
            List<CurrencyGainPriceRedisBo> priceRedisBos = new ArrayList<>();
            LogTrace.info(LogTraceKeysUtils.COIN_MARKET_CAP_API_SCHEDULED_TITLE, LogTraceKeysUtils.DATA, "解析cmc货币数据开始");
            LogTrace.info(LogTraceKeysUtils.COIN_MARKET_CAP_API_SCHEDULED_TITLE, "size", dataObject.size() + "");
            int count = 0;
            int size = 0;
            for (String key : dataObject.keySet()) {
                //解析CMC的货币数据，转换为定义的实体类
                CmcTickerDataVo tickerData = dataObject.getObject(key, CmcTickerDataVo.class);
                //定义Hbase的rowKey = 币种ID + 当前的时间到分钟
                String rowKey = tickerData.getWebsite_slug() + "_" + nowString;
                //定义hbase中的数据结构
                CurrencyInfoHbase currencyInfoHbase = new CurrencyInfoHbase();
                currencyInfoHbase.setRowKey(rowKey);
                currencyInfoHbase.setCmcId(tickerData.getWebsite_slug());
                currencyInfoHbase.setCreateTime(now);
                currencyInfoHbases.add(currencyInfoHbase);
                CmcCurrencyInfo cmcCurrencyInfo = new CmcCurrencyInfo();
                cmcCurrencyInfo.setCreateTime(now);
                cmcCurrencyInfo.setId(tickerData.getWebsite_slug());
                cmcCurrencyInfo.setName(tickerData.getName());
                cmcCurrencyInfo.setRank(tickerData.getRank());
                cmcCurrencyInfo.setSymbol(tickerData.getSymbol());
                cmcCurrencyInfo.setAvailableSupply(tickerData.getCirculating_supply());
                cmcCurrencyInfo.setTotalSupply(tickerData.getTotal_supply());
                cmcCurrencyInfo.setMaxSupply(tickerData.getMax_supply());
                CmcTickerDataVo.Quotes usd = tickerData.getQuotes().get("USD");
                if (MathUtils.isNumeric(usd.getPrice())) {

                    BigDecimal price = new BigDecimal(usd.getPrice());
                    //获取当前货币的最高价 放入缓存
                    String coin_height_price_usd =
                            redisServer.get(RedisKeysUtils.COIN_HEIGHT_PRICE_USD + tickerData.getWebsite_slug());
                    if (MathUtils.isNotNumeric(coin_height_price_usd)) {
                        redisServer.set(RedisKeysUtils.COIN_HEIGHT_PRICE_USD + tickerData.getWebsite_slug(), usd.getPrice());
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(coin_height_price_usd);
                        if (bigDecimal.doubleValue() < price.doubleValue()) {
                            redisServer.set(RedisKeysUtils.COIN_HEIGHT_PRICE_USD + tickerData.getWebsite_slug(), usd.getPrice());
                        }
                    }
                    //获取当前货币的最最低价 放入缓存
                    String coin_low_price_usd = redisServer.get(RedisKeysUtils.COIN_LOW_PRICE_USD + tickerData.getWebsite_slug());
                    if (MathUtils.isNotNumeric(coin_low_price_usd)) {
                        redisServer.set(RedisKeysUtils.COIN_LOW_PRICE_USD + tickerData.getWebsite_slug(), usd.getPrice());
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(coin_low_price_usd);
                        if (bigDecimal.doubleValue() > price.doubleValue()) {
                            redisServer.set(RedisKeysUtils.COIN_LOW_PRICE_USD + tickerData.getWebsite_slug(), usd.getPrice());
                        }
                    }
                }
                cmcCurrencyInfo.setPriceUsd(usd.getPrice());
                cmcCurrencyInfo.setVolume24hUsd(usd.getVolume_24h());
                cmcCurrencyInfo.setMarketCapUsd(usd.getMarket_cap());
                cmcCurrencyInfo.setPercentChange1h(usd.getPercent_change_1h());
                cmcCurrencyInfo.setPercentChange24h(usd.getPercent_change_24h());
                cmcCurrencyInfo.setPercentChange7d(usd.getPercent_change_7d());

                CmcTickerDataVo.Quotes cny = tickerData.getQuotes().get("CNY");
                if (MathUtils.isNumeric(cny.getPrice())) {
                    BigDecimal price = new BigDecimal(cny.getPrice());
                    String coin_height_price_cny =
                            redisServer.get(RedisKeysUtils.COIN_HEIGHT_PRICE_CNY + tickerData.getWebsite_slug());
                    if (MathUtils.isNotNumeric(coin_height_price_cny)) {
                        redisServer.set(RedisKeysUtils.COIN_HEIGHT_PRICE_CNY + tickerData.getWebsite_slug(), cny.getPrice());
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(coin_height_price_cny);
                        if (bigDecimal.doubleValue() < price.doubleValue()) {
                            redisServer.set(RedisKeysUtils.COIN_HEIGHT_PRICE_CNY + tickerData.getWebsite_slug(), cny.getPrice());
                        }
                    }
                    String coin_low_price_cny = redisServer.get(RedisKeysUtils.COIN_LOW_PRICE_CNY + tickerData.getWebsite_slug());
                    if (MathUtils.isNotNumeric(coin_low_price_cny)) {
                        redisServer.set(RedisKeysUtils.COIN_LOW_PRICE_CNY + tickerData.getWebsite_slug(), cny.getPrice());
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(coin_low_price_cny);
                        if (bigDecimal.doubleValue() > price.doubleValue()) {
                            redisServer.set(RedisKeysUtils.COIN_LOW_PRICE_CNY + tickerData.getWebsite_slug(), cny.getPrice());
                        }
                    }
                }
                cmcCurrencyInfo.setPriceCny(cny.getPrice());
                cmcCurrencyInfo.setVolume24hCny(cny.getVolume_24h());
                cmcCurrencyInfo.setMarketCapCny(cny.getMarket_cap());

                cmcCurrencyInfo.setLastUpdated(tickerData.getLast_updated());

                Put put = new Put(rowKey.getBytes());//row kye
                Map<String, Object> map = JSON.parseObject(JSON.toJSONString(cmcCurrencyInfo)).getInnerMap();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    if (entry.getValue() != null) {
                        put.addColumn(HbaseTableUtils.CURRENCY_INFO_TABLE_FAMILY.getBytes(),
                                Bytes.toBytes(entry.getKey()),
                                Bytes.toBytes(entry.getValue().toString())
                        );
                    }
                }
                cmcCurrencyInfos.add(cmcCurrencyInfo);
                putList.add(put);
                //hbaseConnectionFactory.tablePut(table, put);
                if (MathUtils.isNumeric(cmcCurrencyInfo.getPriceCny())) {
                    CurrencyGainPriceRedisBo priceRedisBo = new CurrencyGainPriceRedisBo(
                            cmcCurrencyInfo.getId(),
                            cmcCurrencyInfo.getPercentChange1h(),
                            Double.valueOf(cmcCurrencyInfo.getPriceCny())
                    );
                    priceRedisBos.add(priceRedisBo);
                }

                count++;
                size++;
                if (count >= 500 || (size == dataObject.size() - 1)) {
                    if (CollectionUtil.isNotBlank(putList)) {
                        hbaseConnectionFactory.tablePut(table, putList);
                        count = 0;
                        putList = new ArrayList<>();
                    }
                }

            }
            LogTrace.info(LogTraceKeysUtils.COIN_MARKET_CAP_API_SCHEDULED_TITLE, LogTraceKeysUtils.DATA, "解析cmc货币数据完成");
            redisCacheComponent.setCurrencyGainPriceRedisBo(priceRedisBos);

            hbaseConnectionFactory.closeAll(connection, table);
            currencyInfoHbaseService.insertBatch(currencyInfoHbases);
            LogTrace.info(LogTraceKeysUtils.COIN_MARKET_CAP_API_SCHEDULED_TITLE, LogTraceKeysUtils.DATA, "cmc货币数据入库完成");
        } catch (HbaseCloseExcetion | HbaseGetTableExcetion | HbaseTablePutExcetion | HbaseConnectionExcetion e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        if (cmcCurrencyInfos.size() > 5) {
            cmcCurrencyInfos.sort((CmcCurrencyInfo c1, CmcCurrencyInfo c2) -> {
                if (MathUtils.isNotNumeric(c1.getRank())
                        && MathUtils.isNotNumeric(c2.getRank())) {
                    return 0;
                } else if (MathUtils.isNotNumeric(c1.getRank())) {
                    return 1;
                } else if (MathUtils.isNotNumeric(c2.getRank())) {
                    return -1;
                }
                BigDecimal c1BigDecimal = new BigDecimal(c1.getRank());
                BigDecimal c2BigDecimal = new BigDecimal(c2.getRank());
                return c2BigDecimal.compareTo(c1BigDecimal);
            });
            List<CmcCurrencyInfo> infos = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                infos.add(cmcCurrencyInfos.get(i));
            }
            redisServer.set(RedisKeysUtils.COIN_FIVE_RANK, infos);
        }
        return cmcCurrencyInfos;
    }


    public CmcCurrencyGlobalInfo insertCurrencyGlobalInfo(JSONObject resultJson) {
        try {
            Connection connection = hbaseConnectionFactory.getConnection();
            Table table = hbaseConnectionFactory.getTable(connection, HbaseTableUtils.CURRENCY_GLOBAL_INFO_TABLE_NAME);
            Date now = new Date();
            String nowString = DateUtils.dateFormatString(now, DateUtils.format_ymdhm);
            JSONObject dataObject = resultJson.getJSONObject("data");
            if (dataObject == null) {
                return null;
            }
            CmcGobalDataVo gobalDataVo = dataObject.toJavaObject(CmcGobalDataVo.class);
            CmcCurrencyGlobalInfo cmcCurrencyGlobalInfo = new CmcCurrencyGlobalInfo();
            cmcCurrencyGlobalInfo.setCreateTime(now);
            cmcCurrencyGlobalInfo.setActiveCryptocurrencies(gobalDataVo.getActive_cryptocurrencies());
            cmcCurrencyGlobalInfo.setActiveMarkets(gobalDataVo.getActive_markets());
            cmcCurrencyGlobalInfo.setBitcoinPercentageOfMarketCap(gobalDataVo.getBitcoin_percentage_of_market_cap());

            CmcGobalDataVo.Quotes usd = gobalDataVo.getQuotes().get("USD");
            cmcCurrencyGlobalInfo.setTotalMarketCapUsd(usd.getTotal_market_cap());
            cmcCurrencyGlobalInfo.setTotal24hVolumeUsd(usd.getTotal_volume_24h());

            CmcGobalDataVo.Quotes cny = gobalDataVo.getQuotes().get("CNY");
            cmcCurrencyGlobalInfo.setTotalMarketCapCny(cny.getTotal_market_cap());
            cmcCurrencyGlobalInfo.setTotal24hVolumeCny(cny.getTotal_volume_24h());

            cmcCurrencyGlobalInfo.setLastUpdated(gobalDataVo.getLast_updated());

            String rowKey = HbaseTableUtils.CURRENCY_GLOBAL_INFO_TABLE_FAMILY + "_" + nowString;
            Put put = new Put(rowKey.getBytes());//row kye
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(cmcCurrencyGlobalInfo)).getInnerMap();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                put.addColumn(HbaseTableUtils.CURRENCY_INFO_TABLE_FAMILY.getBytes(),
                        Bytes.toBytes(entry.getKey()),
                        Bytes.toBytes(entry.getValue() != null ? entry.getValue().toString() : ""));
            }
            hbaseConnectionFactory.tablePut(table, put);
            hbaseConnectionFactory.closeAll(connection, table);
            CurrencyGlobalInfoHbase currencyGlobalInfoHbase = new CurrencyGlobalInfoHbase();
            currencyGlobalInfoHbase.setRowKey(rowKey);
            currencyGlobalInfoHbase.setCreateTime(now);
            currencyGlobalInfoHbaseService.insertSelective(currencyGlobalInfoHbase);
            return cmcCurrencyGlobalInfo;
        } catch (HbaseCloseExcetion | HbaseGetTableExcetion | HbaseTablePutExcetion | HbaseConnectionExcetion e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 获取超过6%数据
     *
     * @param currentDateString
     * @return
     */
    public Map<String, MoreThanPercentageSixChange> getMoreThanPercentageSixChangeList(String currentDateString) {

        LogTrace.info(LogTraceKeysUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE
                , LogTraceKeysUtils.DATA, "获取超过6%数据");
        LogTrace.info(LogTraceKeysUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE
                , LogTraceKeysUtils.DATA, currentDateString);

        Map<String, MoreThanPercentageSixChange> map = new HashMap<>();
        try {
            String redisString = redisServer.get(RedisKeysUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE + currentDateString);
            LogTrace.info(LogTraceKeysUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE
                    , LogTraceKeysUtils.DATA, "redisString:" + redisString);
            if (StringUtils.isNotBlank(redisString)) {
                JSONObject jsonObject = JSON.parseObject(redisString);
                if (CollectionUtil.isBlank(jsonObject)) {
                    return null;
                }
                for (String key : jsonObject.keySet()) {
                    map.put(key, jsonObject.getObject(key, MoreThanPercentageSixChange.class));
                }
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }

        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE
                    , HbaseTableUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE_TABLE_FAMILY
                    , HbaseTableUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE_TABLE_QUALIFIER
                    , currentDateString);
            LogTrace.info(LogTraceKeysUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE
                    , LogTraceKeysUtils.DATA, "hbaseString:" + data);
            if (StringUtils.isNotBlank(data)) {
                JSONObject jsonObject = JSON.parseObject(data);
                if (CollectionUtil.isBlank(jsonObject)) {
                    return null;
                }
                for (String key : jsonObject.keySet()) {
                    map.put(key, jsonObject.getObject(key, MoreThanPercentageSixChange.class));
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        return map;


    }


    /**
     * 保存涨幅超过6%数据
     *
     * @param cmcInfoMap
     * @return
     */
    public List<MoreThanPercentageSixChange> saveMoreThanPercentageSixChange(Map<String, CmcCurrencyInfo> cmcInfoMap) {
        List<MoreThanPercentageSixChange> moreThanPercentageSixChanges
                = new ArrayList<>();
        List<CurrencyInfo> enableInfos = redisCacheComponent.getCurrencyList();
        try {

            JSONObject mainObject = new JSONObject();

            List<CmcCurrencyInfo> enableCmcInfos = new ArrayList<>();

            for (CurrencyInfo enableInfo : enableInfos) {
                try {
                    CmcCurrencyInfo cmcCurrencyInfo = cmcInfoMap.get(enableInfo.getCmcId());
                    enableCmcInfos.add(cmcCurrencyInfo);
                    if (MathUtils.isNumeric(cmcCurrencyInfo.getPercentChange24h())
                            && Double.valueOf(cmcCurrencyInfo.getPercentChange24h()) > 6) {
                        MoreThanPercentageSixChange sixChange = new MoreThanPercentageSixChange();
                        sixChange.setId(enableInfo.getId());
                        sixChange.setCmcId(cmcCurrencyInfo.getId());
                        sixChange.setName(cmcCurrencyInfo.getName());
                        if (cmcCurrencyInfo.getCreateTime() == null) {
                            continue;
                        }
                        sixChange.setMinute(DateUtils.dateToLocalDateTime(cmcCurrencyInfo.getCreateTime()).getMinute());
                        sixChange.setCreateTime(cmcCurrencyInfo.getCreateTime());

                        String key = cmcCurrencyInfo.getId();

                        mainObject.put(key, sixChange);
                        moreThanPercentageSixChanges.add(sixChange);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    LogTrace.error(e.getMessage(), e);
                }


            }


            if (moreThanPercentageSixChanges.size() == 0 && enableCmcInfos.size() > 0) {
                enableCmcInfos.sort((CmcCurrencyInfo h1, CmcCurrencyInfo h2) -> {
                    if (MathUtils.isNotNumeric(h1.getPercentChange24h())
                            && MathUtils.isNotNumeric(h2.getPercentChange24h())) {
                        return 0;
                    } else if (MathUtils.isNotNumeric(h1.getPercentChange24h())) {
                        return 1;
                    } else if (MathUtils.isNotNumeric(h2.getPercentChange24h())) {
                        return -1;
                    }
                    BigDecimal h1BigDecimal = new BigDecimal(h1.getPercentChange24h());
                    BigDecimal h2BigDecimal = new BigDecimal(h2.getPercentChange24h());
                    return h2BigDecimal.compareTo(h1BigDecimal);
                });
                for (int i = 0; i < (enableCmcInfos.size() < 10 ? enableCmcInfos.size() : 10); i++) {
                    CmcCurrencyInfo cmcCurrencyInfo = enableCmcInfos.get(i);
                    for (CurrencyInfo enableInfo : enableInfos) {
                        if (StringUtils.equals(enableInfo.getCmcId(), cmcCurrencyInfo.getId())) {
                            MoreThanPercentageSixChange sixChange = new MoreThanPercentageSixChange();
                            sixChange.setId(enableInfo.getId());
                            sixChange.setCmcId(cmcCurrencyInfo.getId());
                            sixChange.setName(cmcCurrencyInfo.getName());
                            sixChange.setMinute(DateUtils.dateToLocalDateTime(cmcCurrencyInfo.getCreateTime()).getMinute());
                            sixChange.setCreateTime(cmcCurrencyInfo.getCreateTime());

                            String key = cmcCurrencyInfo.getId();

                            mainObject.put(key, sixChange);
                            moreThanPercentageSixChanges.add(sixChange);
                            break;
                        }
                    }
                }
            }

            String jsonString = mainObject.toJSONString();
            LogTrace.info("保存6%", "data", jsonString);
            currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE
                    , DateUtils.getCurrentDateString()
//                    , DateUtils.getNextDayDateYMD(-1)
                    , HbaseTableUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE_TABLE_FAMILY
                    , HbaseTableUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE_TABLE_QUALIFIER
                    , jsonString);
            redisServer.set(RedisKeysUtils.MORE_THAN_PERCENTAGE_SIX_CHANGE + DateUtils.getCurrentDateString()
                    , jsonString,
                    99999999L);

        } catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }


        return moreThanPercentageSixChanges;
    }


    public Map<String, List<DailyComprehensiveAnalysisInfo>> getDailyCurrencyInfor(String rowkey) {
        Map<String, List<DailyComprehensiveAnalysisInfo>> map = new HashMap<>();
        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_NAME
                    , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_FAMILY
                    , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_QUALIFIER
                    , rowkey);
            if (StringUtils.isBlank(data)) {
                throw new ErrorDataException("获取每日货币数据失败！rowkey：" + rowkey);
            }
            JSONObject mainObject = JSON.parseObject(data);
            for (String key : mainObject.keySet()) {
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if (jsonArray == null) {
                    continue;
                }
                List<DailyComprehensiveAnalysisInfo> dailyComprehensiveAnalysisInfos =
                        jsonArray.toJavaList(DailyComprehensiveAnalysisInfo.class);
                map.put(key, dailyComprehensiveAnalysisInfos);
            }
        } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | HbaseCloseExcetion
                | IOException | ErrorDataException e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
            return null;
        }

        return map;
    }

    public List<DailyComprehensiveAnalysisInfo> saveDailyCurrencyInfor(List<CmcCurrencyInfo> cmcCurrencyInfos) {

        List<DailyComprehensiveAnalysisInfo> dailyComprehensiveAnalysisInfos = new ArrayList<>();

        for (CmcCurrencyInfo info : cmcCurrencyInfos) {
            String rowKey = info.getId() + "@" + DateUtils.getCurrentDateString();
            try {
                String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_NAME
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_FAMILY
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_QUALIFIER
                        , rowKey);
                JSONObject mainObject;
                if (StringUtils.isBlank(data)) {
                    mainObject = new JSONObject();
                } else {
                    mainObject = JSON.parseObject(data);
                }
                DailyComprehensiveAnalysisInfo dailyComprehensiveAnalysisInfo
                        = new DailyComprehensiveAnalysisInfo();
//                dailyComprehensiveAnalysisInfo.setPriceCny(info.getPriceCny());
//                dailyComprehensiveAnalysisInfo.setMarketCapCny(info.getMarketCapCny());
                BeanUtils.copyProperties(info, dailyComprehensiveAnalysisInfo);
                dailyComprehensiveAnalysisInfo.setCreateTime(info.getCreateTime());
                if (MathUtils.isNumeric(info.getAvailableSupply())
                        && MathUtils.isNumeric(info.getVolume24hCny())
                        && MathUtils.isNumeric(info.getPriceCny())) {
                    BigDecimal priceCny = new BigDecimal(info.getPriceCny());
                    BigDecimal availableSupply = new BigDecimal(info.getAvailableSupply());
                    dailyComprehensiveAnalysisInfo.setCirculation24hCny(availableSupply.toString());
                    //dailyComprehensiveAnalysisInfo.setCirculation24hCny(priceCny.multiply(availableSupply).toString());
                    dailyComprehensiveAnalysisInfo.setVolume24hCny(info.getVolume24hCny());
                    dailyComprehensiveAnalysisInfo.setPriceUsd( info.getPriceUsd() );
                }

                //市值排名
                dailyComprehensiveAnalysisInfo.setRank( info.getRank() );
                String key = LocalDateTime.now().getHour() + "";
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if (jsonArray == null) {
                    jsonArray = new JSONArray();
                }
                jsonArray.add(dailyComprehensiveAnalysisInfo);
                mainObject.put(key, jsonArray);
                dailyComprehensiveAnalysisInfos.add(dailyComprehensiveAnalysisInfo);
                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_NAME
                        , rowKey
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_FAMILY
                        , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_QUALIFIER
                        , mainObject.toJSONString());
            } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | IOException | HbaseCloseExcetion e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
                return null;
            }

        }

        return dailyComprehensiveAnalysisInfos;


    }

    public List<TrendsInfo> getGoogleTrends(Date date) {
        try {
            String url = googleTrendsUrl;
            Map<String, Object> map = new HashMap<>();
            List<String> coinIds = new ArrayList<>();
            String timestamp = String.valueOf(System.currentTimeMillis());
            int step = 5;

            List<CurrencyInfo> CurrencyInfos = redisCacheComponent.getDiagnosisCurrencyList();
            for (CurrencyInfo info : CurrencyInfos) {
                if (StringUtils.isNotBlank(info.getCmcId())) {
                    coinIds.add(info.getCmcId());
                }
            }
            List<String> cmcIds = new ArrayList<>();
            for (String cmcId : coinIds) {
                cmcIds.add(cmcId);
            }
            map.put("cmcIds", cmcIds);


            //请求google 趋势api
            String trends = HttpUtils.post(url, JSON.toJSONString(map));
            JSONObject object = JSON.parseObject(trends);
            JSONArray result = object.getJSONArray("result");
            List<TrendsInfo> trendsInfos = new ArrayList<>();
            for (int i = 0; i < cmcIds.size(); i++) {
                TrendsInfo trendsInfo = new TrendsInfo();
                JSONArray scoreArray = result.getJSONObject(i).getJSONArray(cmcIds.get(i));
                BigDecimal scoreStr = new BigDecimal(0);
                int totalScoreStr = 12;
                if (null != scoreArray & scoreArray.size() > 1) {
                    Collections.reverse(scoreArray);
                    for (int k = 0; k < 60; k += step) {
                        JSONObject sc = (JSONObject) scoreArray.get(k);
                        BigDecimal newScoreStr = new BigDecimal(sc.getString("value"));
                        if (!"0".equals(newScoreStr.toString())) {
                            scoreStr = scoreStr.add(newScoreStr);
                        } else {
                            totalScoreStr = totalScoreStr - 1;
                        }
                    }
                    //趋势分数均值
                    if (totalScoreStr>0) {
                        scoreStr = scoreStr.divide(new BigDecimal(totalScoreStr), 1);
                    } else {
                        scoreStr = new BigDecimal(0);
                    }
                }
                //未获取到币种市场热度处理
                else{
                    trendsInfo =    currencyInfoHbaseComponent.getLaseGoogleTrendsByCurrencyInfo(cmcIds.get(i));
                    trendsInfos.add(trendsInfo);
                }


                //趋势得分为空或为null，不存储
                if (!"0".equals(scoreStr) & null != scoreStr) {
                    trendsInfo.setId(cmcIds.get(i));
                    trendsInfo.setCreateTime(date);
                    trendsInfo.setHotSearchTime(timestamp);
                    trendsInfo.setHotSearchIndex(scoreStr);
                    trendsInfo.setMinute(DateUtils.dateToLocalDateTime(date).getMinute());
                    trendsInfos.add(trendsInfo);
                }
                //未获取到币种市场热度处理
                else{
                    trendsInfo =    currencyInfoHbaseComponent.getLaseGoogleTrendsByCurrencyInfo(cmcIds.get(i));
                    trendsInfos.add(trendsInfo);
                }
            }

            BigDecimal totalScore = new BigDecimal(0);

            for (TrendsInfo trendsInfo : trendsInfos) {
                totalScore = totalScore.add(trendsInfo.getHotSearchIndex());
            }

            BigDecimal averageScore = totalScore.divide(new BigDecimal(trendsInfos.size()), 2, BigDecimal.ROUND_DOWN);

            for (TrendsInfo trendsInfo : trendsInfos) {
                trendsInfo.setAverageHotSearchIndex(averageScore);
                BigDecimal marketHeatScore = trendsInfo.getHotSearchIndex().divide(averageScore, 2, BigDecimal.ROUND_DOWN);


                double doubleScore = marketHeatScore.doubleValue();
                trendsInfo.setMarketheat(marketHeatScore);

                if (doubleScore < 0.1) {
                    trendsInfo.setScore(new BigDecimal(1));
                    trendsInfo.setResult("投资者关注度低");
                } else if (0.1 <= doubleScore && doubleScore < 0.2) {
                    trendsInfo.setScore(new BigDecimal(2));
                    trendsInfo.setResult("投资者关注度低");
                } else if (0.2 <= doubleScore && doubleScore < 0.4) {
                    trendsInfo.setScore(new BigDecimal(3));
                    trendsInfo.setResult("投资者关注度较低");
                } else if (0.4 <= doubleScore && doubleScore < 0.6) {
                    trendsInfo.setScore(new BigDecimal(4));
                    trendsInfo.setResult("投资者关注度较低");
                } else if (0.6 <= doubleScore && doubleScore < 0.8) {
                    trendsInfo.setScore(new BigDecimal(5));
                    trendsInfo.setResult("投资者关注度一般");
                } else if (0.8 <= doubleScore && doubleScore < 1.0) {
                    trendsInfo.setScore(new BigDecimal(6));
                    trendsInfo.setResult("投资者关注度一般");
                } else if (1.0 <= doubleScore && doubleScore < 1.2) {
                    trendsInfo.setScore(new BigDecimal(7));
                    trendsInfo.setResult("投资者关注度较高");
                } else if (1.2 <= doubleScore && doubleScore < 1.4) {
                    trendsInfo.setScore(new BigDecimal(8));
                    trendsInfo.setResult("投资者关注度较高");
                } else if (1.4 <= doubleScore && doubleScore < 1.6) {
                    trendsInfo.setScore(new BigDecimal(9));
                    trendsInfo.setResult("投资者关注度高");
                } else if (doubleScore >= 1.6) {
                    trendsInfo.setScore(new BigDecimal(10));
                    trendsInfo.setResult("投资者关注度高");
                }
            }

            for (TrendsInfo trendsInfo : trendsInfos) {


                String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_MARKET_HEAT_TABLE_NAME
                        , HbaseTableUtils.MARKET_HEAT_TABLE_NAME_FAMILY
                        , HbaseTableUtils.MARKET_HEAT_TABLE_NAME_QUALIFIER
                        , trendsInfo.getId() + "@"
                                + DateUtils.getCurrentDateString());

                JSONObject mainObject;
                if (StringUtils.isBlank(data)) {
                    mainObject = new JSONObject();
                } else {
                    mainObject = JSON.parseObject(data);
                }
                String key = String.valueOf(DateUtils.dateToLocalDateTime(trendsInfo.getCreateTime()).getHour());
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if (jsonArray == null) {
                    jsonArray = new JSONArray();
                }
                jsonArray.add(trendsInfo);
                mainObject.put(key, jsonArray);

                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.DAILY_MARKET_HEAT_TABLE_NAME
                        , trendsInfo.getId() + "@"
                                + DateUtils.getCurrentDateString()
                        , HbaseTableUtils.MARKET_HEAT_TABLE_NAME_FAMILY
                        , HbaseTableUtils.MARKET_HEAT_TABLE_NAME_QUALIFIER
                        , mainObject.toJSONString());
            }
            return trendsInfos;

        } catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }


        return null;
    }


    public CmcCurrencyGlobalInfo getLastGlobal() {
        CurrencyGlobalInfoHbase descRowKey =
                currencyGlobalInfoHbaseService.selectByCreateTime("desc");
        try {
            Map<String, Object> lastMap = hbaseBaseQueryComponent.selectData(
                    HbaseTableUtils.CURRENCY_GLOBAL_INFO_TABLE_NAME, descRowKey.getRowKey());
            return JSON.parseObject(JSON.toJSONString(lastMap), CmcCurrencyGlobalInfo.class);
        } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | HbaseCloseExcetion | IOException e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        return null;
    }


    public List<CmcCurrencyInfo> getLastTicker() {

        Date maxCreateTime = currencyInfoHbaseService.selectMaxMinCreateTime("desc");
        return this.getCmcInfosByDate(maxCreateTime);
    }

    /**
     * 根据创建时间获取货币数据
     *
     * @param date
     * @return
     */
    public List<CmcCurrencyInfo> getCmcInfosByDate(Date date) {
        List<CmcCurrencyInfo> cmcCurrencyInfos = new ArrayList<>();
        date = currencyInfoHbaseService.selectAfterNearDate(DateUtils.dateFormatString(date, DateUtils.format_ymdhms));
        LogTrace.info("根据创建时间获取货币数据", "NearDate", DateUtils.dateFormatString(date, DateUtils.format_ymdhms));
        CurrencyInfoHbase searchInfoHbase = new CurrencyInfoHbase();
        searchInfoHbase.setCreateTime(date);
        List<CurrencyInfoHbase> currencyInfoHbases = currencyInfoHbaseService.selectByEntityList(searchInfoHbase);
        for (CurrencyInfoHbase infoHbase : currencyInfoHbases) {
            String rowKey = infoHbase.getRowKey();
            try {
                Map<String, Object> map = hbaseBaseQueryComponent.selectData(
                        HbaseTableUtils.CURRENCY_INFO_TABLE_NAME, rowKey);
                if (CollectionUtil.isBlank(map)) {
                    continue;
                }
                CmcCurrencyInfo cmcInfo =
                        JSON.parseObject(JSON.toJSONString(map), CmcCurrencyInfo.class);
                cmcCurrencyInfos.add(cmcInfo);
            } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | HbaseCloseExcetion | IOException e) {
                LogTrace.error(e.getMessage(), e);
            }

        }
        return cmcCurrencyInfos;
    }
}
